#!/usr/bin/python3
# _*_ coding:utf-8 _*_
# @Time: 2023/3/22 10:24
# @Author: wen_fei
# @Email: wenfei6316@163.com
# @File: ParseArgs.py
# @Project: ParseArgs

import argparse
import logging
import platform
import re
import os

class ParseArgs():
    def __int__(self):
        self.parser = None
        self.build_package_group = None
        self.LLVM_BUILD_DIR = None
        self.LLVM_PROJECT_DIR = None
        self.OUT_PATH = None
        self.REPOROOT_DIR = None
        pass

    def parse_args(self):
        # description 用于描述该程序用来做什么
        self.parser = argparse.ArgumentParser(description="you should add those parameter")
        # 创建一个互斥组，确保互斥组中只有一个参数在命令行中可用
        # 参考用例：https://blog.csdn.net/weixin_36670529/article/details/113783239
        self.build_package_group = self.parser.add_mutually_exclusive_group()
        self.build_package_group.add_argument(
            '--skip-build',
            '-sb',
            # store_true 是指带触发action时为真，不触发则为假。通俗讲是指运行程序是否带参数
            # 参考用例：https://blog.csdn.net/qq_43799400/article/details/119034026
            action='store_true',
            default=False,
            help='Omit the build, perform the packaging step directly.')

        self.build_package_group.add_argument(
            '--skip-package',
            '-sp',
            action='store_true',
            default=False,
            help='Omit the packaging, perform the packaging step directly.')
        self.parser.add_argument(
            '--enable-assertions',
            action='store_true',
            default=False,
            help='Apply assertions, some parameters are affected.')

        known_platforms = ('windows', 'libs', 'lldb-mi', 'lldb-server', 'linux', 'check-api')
        # 将known_platforms的值以, + 空格串联起来，结果为"windows, libs, lldb-mi, lldb-server, linux, check-api"
        known_platforms_str = ', '.join(known_platforms)

        class SeparatedListByCommaAction(argparse.Action):
            # 把类当做一个方法使用
            # 参考用例：https://zhuanlan.zhihu.com/p/165245990
            def __call__(self, parser, namespace, vals, option_string):
                for val in vals.split(','):
                    if val in known_platforms:
                        continue
                    else:
                        error = '\'{}\' invalid.  Choose from {}'.format(val, known_platforms)
                        raise argparse.ArgumentError(self, error)
                setattr(namespace, self.dest, vals.split(','))

        self.parser.add_argument(
            '--no-build',
            action=SeparatedListByCommaAction,
            default=list(),
            help='Don\'t build toolchain for specified platforms.  Choices: ' + known_platforms_str)
        return self.parser.parse_args()

    def discover_paths(self):
        # 获取当前脚本所在目录的绝对路径
        self.LLVM_BUILD_DIR = os.path.abspath(os.path.dirname(__file__))
        # 获取脚本所在的目录的父目录名称
        parent_of_llvm_build = os.path.basename(os.path.dirname(self.LLVM_BUILD_DIR))
        if parent_of_llvm_build == 'toolchain':
            # 设置编译root路径
            self.REPOROOT_DIR = os.path.abspath(os.path.join(self.LLVM_BUILD_DIR, '../..'))
        else:
            assert parent_of_llvm_build == 'llvm-project'
            self.REPOROOT_DIR = os.path.abspath(os.path.join(self.LLVM_BUILD_DIR, '../../..'))

        # 设置llvm-project路径
        self.LLVM_PROJECT_DIR = os.path.join(self.REPOROOT_DIR, 'toolchain', 'llvm-project')
        # 设置out路径
        self.OUT_PATH = os.path.join(self.REPOROOT_DIR, 'out')

class ClangVersion(object):
    """Parse and save clang version from version file."""

    def __init__(self, version_file):
        self._parse_version_file(version_file)

    @staticmethod
    def _parse(text, key):
        return re.findall(r'%s\s+(\d+)' % key, text)[0]

    def _parse_version_file(self, version_file):
        with open(version_file, 'r') as fp:
            text = fp.read()
        self.major = self._parse(text, 'CLANG_VERSION_MAJOR')
        self.minor = self._parse(text, 'CLANG_VERSION_MINOR')
        self.patch = self._parse(text, 'CLANG_VERSION_PATCHLEVEL')

    def long_version(self):
        return '.'.join([self.major, self.minor, self.patch])

    def short_version(self):
        return '.'.join([self.major, self.minor])

    def major_version(self):
        return self.major

if __name__ == '__main__':
    #parseArgs = ParseArgs()
    # print(parseArgs.parse_args().no_build)
    # logging.basicConfig(level=logging.INFO)
    # str = """
    #CLANG_VERSION_MAJOR
    #"""
    #print(platform.system())
    #print(platform.machine())
    #print("linux-x86_64"[:-3])
    # logging.getLogger().error("Hello World")
    print (os.popen('where python3').read().strip())

    pass

